const express = require('express')
const boom = require('boom')
const userRouter = require('./user')
const ebookRouter = require('./book')
const jwtAuth = require('./jwt')

const Result = require('../modules/Result')
//注册路由
const router = express.Router()

router.use(jwtAuth)

router.use('/user',userRouter)
router.use('/ebook',ebookRouter)


router.get('/',function(req,res){
    res.send('dajiahaocaishizhenhao')
})

router.use((req,res,next)=>{
    next(boom.notFound('接口不存在'))
})

router.use((err,req,res,next)=>{
    
    if(err.name&&err.name=='UnauthorizedError'){
        const {status = 401} = err
        new Result(null,'Token验证失败',{
            error:status,
            errMsg:err.message
        }).jwtError(res.status(status))
    }else{
        const msg = (err&&err.message)||'系统错误'
        const statusCode = (err.output&&err.output.statusCode) || 500
        const errMsg = (err.output&&err.output.payload&&err.output.error) || err.message
        new Result(null,msg,{
            error:statusCode,
            errMsg
        }).fail(res.status(statusCode))

    }


    
})


module.exports = router